package de.gympu.gympulan.core.pluginutil;

import java.util.Collection;
import java.util.Iterator;

import org.java.plugin.Plugin;
import org.java.plugin.PluginManager;
import org.java.plugin.boot.ApplicationPlugin;
import org.java.plugin.registry.Extension;
import org.java.plugin.registry.ExtensionPoint;

import de.gympu.gympulan.core.plugins.gplloggingplugin.GPLLogging;
import de.gympu.gympulan.core.GymPuLan;
import de.gympu.gympulan.core.GymPuLanImpl;
public class PluginLoader<E> {
	
	private ApplicationPlugin base;
	private E[] objects;
	
	private Iterator<?> it;
	
	public PluginLoader(ApplicationPlugin base,String pluginName) {
		this.base = base;
	
		// ExtensionPoint extPoint = base.getManager().getRegistry().getExtensionPoint(base.getDescriptor().getId(), pluginName);		
		ExtensionPoint extPoint = GymPuLan.getPluginManager().getRegistry().getExtensionPoint(base.getDescriptor().getId(), pluginName);		

		it = extPoint.getConnectedExtensions().iterator();		
	}
	
	public PluginLoader(Plugin base, String pluginID, Object baseObject, String pluginName) {
		PluginManager mngr = PluginManager.lookup(base);
		System.out.println(mngr);
        Collection<Extension> extensions = mngr.getRegistry().getExtensionPoint(pluginID, pluginName).getConnectedExtensions();
		it = extensions.iterator();
	}
	
	public PluginContainer<E> getNext() {
		if(it.hasNext()) {
			Extension ext = (Extension) it.next();
        	try {
	        	// base.getManager().activatePlugin(ext.getDeclaringPluginDescriptor().getId());
        		// GymPuLan.getPluginManager().activatePlugin(ext.getDeclaringPluginDescriptor().getId());
				ClassLoader classLoader = GymPuLan.getPluginManager().getPluginClassLoader(ext.getDeclaringPluginDescriptor());
				Class<?> toolCls = classLoader.loadClass(ext.getParameter("class").valueAsString());
				E object = (E) toolCls.newInstance();
				
				return new PluginContainer<E>(object,ext);
        	}
        	catch(Exception e) {
        		// e.printStackTrace();
        		throw new PluginLoadException("Fehler beim Laden des Plugins " + ext.getId() + "(" + e + ")");
        	}
		}
		
		return null;
	}
	
	public boolean hasNext() {
		return it.hasNext();
	}
}
